package com.ch.android.lookforkotlinv2.activity

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.SurfaceView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.ch.android.baselib.SpUtil
import com.ch.android.baselib.SpUtil.getSessionId
import com.ch.android.baselib.SpUtil.getUserId
import com.ch.android.lookforkotlinv2.AppConst
import com.ch.android.lookforkotlinv2.R
import com.ch.android.lookforkotlinv2.databinding.ActivityWatchLiveBinding
import com.ch.android.lookforkotlinv2.vm.WatchLiveModel
import com.ch.android.networklib.RequestClient
import com.ch.android.networklib.data.API_STATUS_OK
import com.ch.android.networklib.data.LiveListItemData
import com.ch.android.networklib.data.WatchLiveData
import io.agora.rtc2.Constants
import io.agora.rtc2.IRtcEngineEventHandler
import io.agora.rtc2.RtcEngine
import io.agora.rtc2.video.VideoCanvas
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 观看直播
 */
class WatchLiveActivity : AppCompatActivity() {
    companion object {
        private const val TAG = "WatchLiveActivity"
        private const val PARAM_ITEM = "item"
        // 启动 WatchLiveActivity
        fun start(context: Context, item: LiveListItemData) {
            val intent = Intent(context, WatchLiveActivity::class.java).apply {
                putExtra(PARAM_ITEM, item)
            }
            context.startActivity(intent)
        }
    }

    /**
     * 主播Id
     */
    private var liveUserId = 0
    private lateinit var item: LiveListItemData
    private var mWatchLiveData: WatchLiveData? = null

    // 使用 by lazy (延迟初始化) 代替 lateinit var
    private val mBinding : ActivityWatchLiveBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_watch_live)
    }
    // 使用 by lazy (延迟初始化) 代替 lateinit var
    private val mModel: WatchLiveModel by lazy {
        ViewModelProvider(this)[WatchLiveModel::class.java]
    }
    /**
     * Agora Rtc Engine 声网引擎
     */
    private lateinit var mRtcEngine: RtcEngine

    /**
     * 声网SDK回调
     */
    private val mRtcEventHandler: IRtcEngineEventHandler = object : IRtcEngineEventHandler() {
        // 监听频道内的远端主播，获取主播的 uid 信息。
        override fun onUserJoined(uid: Int, elapsed: Int) {
            Log.d(TAG, "onUserJoined: 接入直播uid:$uid elapsed:$elapsed")
            //二次进入看直播界面时，onUserJoined会被触发多次，所以需要判断当前用户是否已经加入房间，避免重复加入
            if (liveUserId == uid) {
                return
            }
            liveUserId = uid
            lifecycleScope.launch(Dispatchers.Main) {
                // 从 onUserJoined 回调获取 uid 后，调用 setupRemoteVideo，设置远端视频视图。
                setupRemoteVideo(uid)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (!intent.hasExtra(PARAM_ITEM)) {
            throw IllegalArgumentException("WatchLiveActivity must be started by intent with LiveListItemData")
        }
        item = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra(PARAM_ITEM, LiveListItemData::class.java)!!
        } else {
            intent.getParcelableExtra(PARAM_ITEM)!!
        }
        mBinding.lifecycleOwner = this

        mBinding.model = mModel
        lifecycleScope.launch {
            requestLiveUrl()
        }
    }

    private suspend fun requestLiveUrl() {
        val resultData = RequestClient.getApiService(this).watchLive(
            SpUtil.getSP().getSessionId(),
            item.liveId.toInt()
        )
        if (resultData.status == API_STATUS_OK) {
            mWatchLiveData = resultData.result
            initAndJoinChannel()
        } else {
            Toast.makeText(this, resultData.message, Toast.LENGTH_SHORT).show()
        }
    }
    /**
     * 初始化RtcEngine
     */
    private fun initAndJoinChannel() {
        // 设置音士频的参数
        try {
            mRtcEngine = RtcEngine.create(this.baseContext, AppConst.AGORA_APP_ID, mRtcEventHandler)
            // 视频默认禁用，你需要调用 enableVideo 启用视频流。
            mRtcEngine.enableVideo()
            mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING)
            // 根据场景设置用户角色为：BROADCASTER（主播） 或 AUDIENCE（观众）。
            mRtcEngine.setClientRole(Constants.CLIENT_ROLE_AUDIENCE)

            // 创建一个 SurfaceView 对象，并将其作为 FrameLayout 的子对象。
            val surfaceView = SurfaceView(this)
            mBinding.subVideoContainer.addView(surfaceView)
            // 将 SurfaceView 对象传入 Agora，以渲染本地视频。
            mRtcEngine.setupLocalVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, 0))
            val userId = SpUtil.getSP().getUserId()
            mRtcEngine.joinChannel(mWatchLiveData!!.agoraToken, mWatchLiveData!!.channelName, "", userId)
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }

    private fun setupRemoteVideo(uid: Int) {
        val surfaceView = SurfaceView(this)
        surfaceView.setZOrderMediaOverlay(true)
        mBinding.fullscreenVideoContainer.addView(surfaceView)
        mRtcEngine.setupRemoteVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, uid))
    }
}